<?php

namespace app\admin\model;

use fast\Random;
use think\Model;

class Device extends Model
{
    // 表名
    protected $name = 'device';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    const DELETE_TIME = 0;

    // 追加属性
    protected $append = [

    ];

    /**
     * 检查数据是否存在
     * @param $id
     * @return false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkIsExist($id)
    {
        $info = $this->field('id')
            ->where('id', $id)
            ->where('deletetime', self::DELETE_TIME)
            ->find();
        if (!$info) {
            return false;
        }
        return $info['id'];
    }

    /**
     * 关联分类
     * @return \think\model\relation\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 关联用户
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'master_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function model()
    {
        return $this->belongsTo('DeviceModel', 'model_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 关联省份
     * @return \think\model\relation\BelongsTo
     */
    public function province()
    {
        return $this->belongsTo('area', 'province_id', 'id', ['level' => 1], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 生成设备编号
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function generateIdentifierCode()
    {
        $identifier_code = Random::numeric(8);
        $info = $this->field('id')
            ->where('identifier_code', $identifier_code)
            ->where('deletetime', self::DELETE_TIME)
            ->find();
        if ($info) {
            return $this->generateIdentifierCode();
        } else {
            return $identifier_code;
        }
    }

    /**
     * 生成设备序列号
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function generateDeviceSn()
    {
        $device_sn = Random::alnum(12);
        $info = $this->field('id')
            ->where('device_sn', $device_sn)
            ->where('deletetime', self::DELETE_TIME)
            ->find();
        if ($info) {
            return $this->generateDeviceSn();
        } else {
            return $device_sn;
        }
    }
    
}
